/*
 * @Author: your name
 * @Date: 2020-12-21 13:56:22
 * @LastEditTime: 2020-12-21 14:19:12
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit: 
 * @FilePath: \basicjs\event\xhr.js
 */
class HD{
    options = {
        responseType : 'json'
    }
    constructor(method='GET',url,data=null,options){
        this.method = method;
        this.url = url;
        //对表单数据进行格式化
        this.data = this.formData(data)
        //进行参数合并,重复的会后面的修改掉前面的
        Object.assign(this.options,options)
    }

    formData(data){
        if(typeof data != 'object' || data == null){
            data = {};
        }
        let form = new FormData();
        for(const [name,value] of Object.entries(data)){
            form.append(name,value);
        }
        return form;
    }

    //发送get请求
    static get(url,options){
        return new this('GET',url,null,options).xhr();
    }

    //发送post请求
    static post(url,data,options){
        return new this('POST',url,data,options).xhr();
    }

    xhr(){
        return new Promise((resolve,reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open(this.method,this.url);
            xhr.responseType = this.options.responseType;
            xhr.send(this.data);
            xhr.onload = function(){
                if(xhr.status != 200){
                    reject({status:xhr.status,error:xhr.statusText});
                }else{
                    resolve(xhr.response);
                }
            }
            xhr.onerror = function(error){
                reject(error)
            }
        });
    }



}
